package com.jt.controller;

import com.jt.service.FileService;
import com.jt.vo.ImageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author Cx
 * @stage JT Of Fourth stage
 * @creat 2020-12-01 14:06
 */
@RestController
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * url: /file
     * 参数: 文件信息[fileImage]
     * 返回值: String
     */
    @RequestMapping("/file")
    public String file(MultipartFile fileImage) throws IOException {
        /* 1.获取图片名字 */
        String name = fileImage.getOriginalFilename();
        /* 2.定义文件目录 */
        String fileDirPath = "E:/testForIO/image";
        /* 3.创建目录 */
        File fileDir = new File(fileDirPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        /* 4.生成文件的全路径 */
        String filePath = fileDirPath + "/" + name;
        File imageFile = new File(filePath);
        /* 5.实现文件的上传 */
        fileImage.transferTo(imageFile);
        return "File upload successfully!!!";
    }

    /**
     * 实现文件上传
     * url: /pic/upload?dir=image
     * 参数: uploadFile
     * 返回值: ImageVO对象
     */
    @RequestMapping("/pic/upload")
    public ImageVo upload(MultipartFile uploadFile) {
        return fileService.upload(uploadFile);
    }

}
